﻿using System;
using System.Linq;
using System.Text;
using System.Web.Services;
using System.Web.UI.WebControls;
using ZHDJ.Core.Util;
using ZHDJ.Data.Models;
using ZHDJ.Data.Models.JoinParty;
using ZHDJ.Data.Models.Org;
using ZHDJ.JoinParty.BLL;
using ZHDJ.WebPage;
using ZHDJ.WebPage.Master;

namespace ZHDJ.Web.Portal
{
    public partial class JoinPartyNotice : UseMorePageMasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckLogin(true, true);
            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
        }

        protected void LoadData()
        {
            //判断当前用户是否已登陆
            CheckLogin(true);
            //判断当前用户是否已经入党

            this.hdBranchID.Text = CurrentUser.BranchID;
            PartyOrgMember member = DB.PartyOrgMembers.Find(this.CurrentUser.LoginID);
            if (member == null)
            {
                return;
            }
            txtUserName.Text = member.UserName;
            txtMobileNo.Text = member.MobileNo;
            rblGender.SelectedValue = member.Gender == "" ? "0" : member.Gender;
            ppBranch.Text = ControlBusiness.GetBranchPickerText(member.BranchID);
            txtIDCard.Text = member.IdentityCard;
            txtEmail.Text = member.Email;
            if (member.Birthday != null)
            {
                dpBirthday.Text = Convert.ToDateTime(member.Birthday).ToString("yyy-MM-dd");
            }
            txtNation.Text = member.Nation;
            txtQQNumber.Text = member.QQNumber;
            txtWeiXinNo.Text = member.WeiXinNo;
            txtNativePlace.Text = member.NativePlace;
            this.ddlEducation.SelectedValue = member.Educational;
            txtWorkUnit.Text = member.WorkUnit;
            txtAddress.Text = member.Address;
            txtWorkAddress.Text = member.WorkAddress;
            dpApplyTime.Text = Convert.ToDateTime(member.CreateTime).ToString("yyy-MM-dd");
        }

        public void BindData()
        {
            var pickerurl = String.Format("../app/Share/Picker/BranchToMemberPicker_JoinParty.aspx?ids=<script>{0}</script>",
                hdBranchID.GetValueReference());
            ppBranch.OnClientTrigger2Click = Window1.GetSaveStateReference(hdBranchID.ClientID, ppBranch.ClientID)
                                              + Window1.GetShowReference(pickerurl);

            StringBuilder js = new StringBuilder();
            js.AppendFormat(@"
                ; var pickerClientID = '{0}';
                  var pickerHdClientID = '{1}';
                  F(pickerClientID).setValue('');
                  F(pickerHdClientID).setValue('');
", ppBranch.ClientID, hdBranchID.ClientID);
            ppBranch.OnClientTrigger1Click = js.ToString();
        }

        public static string GetNotice()
        {
            var op = DB.PartyJoinPromises.Find("PromiseID");
            return op.Promise;
        }

        private void SaveData(bool isSubmit = false)
        {
            bool bResult = false;
            bool isAdd = false;
            //验证身份证与手机号码的唯一性
            //if (ModuleUtil.CheckLoginIDCount(txtIDCard.Text.Trim(), this.ppUser.Value) && txtIDCard.Text.Trim() != "")
            //{
            //    Alert.Show(string.Format("你输入的身份证：{0}已经存在，请确认！", txtIDCard.Text.Trim()), String.Empty, ActiveWindow.GetHideReference());
            //    return;
            //}
            //if (ModuleUtil.CheckLoginIDCount(txtMobileNo.Text.Trim(), this.ppUser.Value) && txtMobileNo.Text.Trim() != "")
            //{
            //    Alert.Show(string.Format("你输入的手机号码：{0}已经存在，请确认！", txtMobileNo.Text.Trim()), String.Empty, ActiveWindow.GetHideReference());
            //    return;
            //}
            PartyOrgMember om = DB.PartyOrgMembers.Find(this.CurrentUser.LoginID);
            if (om == null)
                om = new PartyOrgMember();
            else
                om.ModifyTimeEx = DateTime.Now;
            om.BranchID = hdBranchID.Text;
            om.Gender = this.rblGender.SelectedValue;
            om.IdentityCard = this.txtIDCard.Text.Trim();
            if (!string.IsNullOrEmpty(this.dpBirthday.Text))
            {
                om.Birthday = Convert.ToDateTime(this.dpBirthday.Text);
            }
            if (!string.IsNullOrEmpty(hdFileID.Text))
            {
                om.ImageUrl = hdFileID.Text;
            }
            om.Nation = this.txtNation.Text.Trim();
            om.NativePlace = this.txtNativePlace.Text.Trim();
            //om.ImageUrl = hdFileID.Value;
            om.Educational = ddlEducation.SelectedValue;
            om.MobileNo = this.txtMobileNo.Text.Trim();
            om.Email = this.txtEmail.Text.Trim();
            om.QQNumber = this.txtQQNumber.Text.Trim();
            om.WeiXinNo = this.txtWeiXinNo.Text.Trim();
            om.Address = this.txtAddress.Text.Trim();
            om.WorkUnit = this.txtWorkUnit.Text.Trim();
            om.WorkAddress = this.txtWorkAddress.Text.Trim();

            PartyJoinApplycation pja = DB.PartyJoinApplycation.Where(a => a.LoginID == this.CurrentUser.LoginID).FirstOrDefault();
            if (pja == null)
            {
                pja = new PartyJoinApplycation();
                //申请ID
                pja.AppllicationID = StringHelper.NewID;
                isAdd = true;
                pja.Status = (int)Enum_ApplyStatus.草稿;
            }
            else if (pja.Status == 2)
            {
                pja = new PartyJoinApplycation();
                //申请ID
                pja.AppllicationID = StringHelper.NewID;
                isAdd = true;
                pja.Status = (int)Enum_ApplyStatus.草稿;
            }
            pja.BranchID = this.hdBranchID.Text;

            om.Address = this.txtAddress.Text.Trim();
            om.WorkUnit = this.txtWorkUnit.Text.Trim();
            om.WorkAddress = this.txtWorkAddress.Text.Trim();

            pja.LoginID = this.CurrentUser.LoginID;
            pja.UserName = txtUserName.Text.Trim();
            pja.CreateTime = Convert.ToDateTime(this.dpApplyTime.Text);
            pja.CreateUserID = this.CurrentUser.LoginID;
            if (isSubmit)  //0:表示保存，1：表示提交
            {
                pja.Status = (int)Enum_ApplyStatus.申请中;
            }
            if (isAdd)
            {
                DB.PartyJoinApplycation.Add(pja);
            }
            bResult = DB.SaveChanges() > 0;//添加用户申请信息、更新用户表基本信息      

            //插入流程步骤信息
            if (isSubmit)
            {
                if (!PartyJoinApplycation.IsApplyOver(pja.AppllicationID))
                {
                    ProcesUtil.CreateProcesStep(pja.AppllicationID, this.hdBranchID.Text, this.CurrentUser.LoginID, txtUserName.Text.Trim());
                }
            }

            if (bResult)
            {
                if (isSubmit)
                {
                    Alert("提交成功！");
                }
                else
                {
                    Alert("请登录个人中心完成信息完善工作！");
                }
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string username = FilterSpecialCharacters.Filter("");
            string phone = FilterSpecialCharacters.Filter(this.txtMobileNo.Text);
            var Registers = DB.JoinPartyRegisters.Where(a => a.UserName == username && a.Statue == false).ToList();
            var Register1s = DB.PartyJoinApplycation.Where(a => a.UserName == username && a.Status != 2).ToList();
            if (Register1s.Count > 0)
            {
                Alert("已经登记，请勿重复登记。");
                //这里应该要推送代办
            }
            else
            {
                JoinPartyRegister omodel = new JoinPartyRegister();
                omodel.ID = StringHelper.NewID;
                omodel.UserName = username;
                omodel.TelephoneNumber = phone;
                omodel.Statue = false;
                omodel.CreateBy = CurrentUser.LoginID;
                omodel.CreateTime = DateTime.Now;
                DB.JoinPartyRegisters.Add(omodel);
                DB.SaveChanges();
                Alert("信息已经登记，请耐心等候联系！");
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveData();
        }

        protected void btnSubmitInfo_Click(object sender, EventArgs e)
        {
            var Registers = DB.PartyJoinApplycation.Where(a => a.LoginID == CurrentUser.LoginID && a.Status != 2).ToList();
            if (Registers.Count > 0)
            {
                Alert("已经登记，请勿重复登记。");
                return;
            }
            SaveData(true);
        }

        protected void filePhoto_FileSelected(object sender, EventArgs e)
        {
            var rs = UpFileBusiness.Upload(filePhoto, CurrentUser.LoginID, "个人头像");
            if (rs.IsSuccess)
            {
                hdFileID.Text = rs.FileID;
                imgPhoto.ImageUrl = "~/" + rs.FileUrl;
                imgPhoto.ImageWidth = Unit.Pixel(200);
            }
        }

        [WebMethod]
        public static string GetRunState(string currentUser)
        {
            PartyOrgMember member = DB.PartyOrgMembers.Find(currentUser);
            return member.runSate;
        }
        [WebMethod]
        public static int GetJoinPartyRegisters(string currentUser)
        {
            var Registers = DB.PartyJoinApplycation.Where(a => a.LoginID == currentUser && a.Status != 2).ToList();
            return Registers.Count;
        }
    }
}